<template>
  <div class="table-wrapper">
    <header ref="tableWrapperHeader" class="table-header-wrapper">
      <SecurityCheckHeader
        title="航线货物关联统计"
        @change="changeHandler"
        @search="searchHandler"
        mode="multiple"
        selectPlaceholder="目的地"
        :optionLists="destination"
        @exportex="exportex"
      />
    </header>
    <main>
      <div class="conten">
        <div class="log_cont">
          <div class="cont" v-for="(item, index) in treeTitles" :key="index" @click="ups(item, index)">
            <div :class="active == index ? 'log_types' : 'log_type'">{{ item.name }}</div>
          </div>
        </div>
        <span>{{ active == 1 ? '单位：件' : '单位：千克' }}</span>
      </div>
      <SecurityCheckTable
        style="height: 700px"
        id="1"
        :footerDate="footerDate"
        :table-cols="tableCols"
        :table-data="tableData"
        row-key="index"
        :height="tableHeight"
        show-summary
        :pagination="false"
        :loading="loading"
      />
    </main>
  </div>
</template>

<script>
import SecurityCheckHeader from '../components/securityCheckHeader.vue'
import SecurityCheckTable from '../components/securityCheckTable.vue'
import { agent, routeall, agentPiece } from '@/api/statistics/statistics.js'
import XLSX from 'xlsx'
import FileSaver from 'file-saver'
export default {
  components: { SecurityCheckHeader, SecurityCheckTable },
  data() {
    return {
      destination: [],
      loading: false,
      tableHeight: '550',
      Company: '件',
      active: 0,
      treeTitles: [
        {
          name: '重量',
        },
        {
          name: '件数',
        },
      ],
      tableCols: [
        {
          title: '目的地',
          dataIndex: 'flightLine',
          key: 'flightLine',
        },
        {
          dataIndex: 'count',
          key: 'count',
          title: '总件数',
          clickHandler: (row, rowIndex) => {
            this.$router.push({
              path: './waybillTable',
              name: 'WaybillTable',
              params: {
                startTime: this.FormData.beginDate,
                endTime: this.FormData.endDate,
                destination: row.flightLine == '合计' ? '' : row.flightLine,
                agentCode: this.FormData.proxyId,
                riskRating: '',
                openResult: '',
              },
            })
          },
        },
        {
          dataIndex: 'highRisk',
          key: 'highRisk',
          title: '普通',
          children: [
            {
              dataIndex: 'highRiskcount',
              key: 'highRiskcount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine == '合计' ? '' : row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '普通',
                  },
                })
              },
            },
            {
              dataIndex: 'mix',
              key: 'mix',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'lowRisk',
          key: 'lowRisk',
          title: '严控',
          children: [
            {
              dataIndex: 'lowRiskCount',
              key: 'lowRiskCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine == '合计' ? '' : row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '严控',
                  },
                })
              },
            },
            {
              dataIndex: 'lowRiskRatio',
              key: 'lowRiskRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'priority',
          key: 'priority',
          prop: 'priority',
          title: '低风险',
          children: [
            {
              dataIndex: 'priorityCount',
              key: 'priorityCount',
              prop: 'priorityCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine == '合计' ? '' : row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '低风险',
                  },
                })
              },
            },
            {
              dataIndex: 'priorityRatio',
              key: 'priorityRatio',
              prop: 'priorityRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'normal',
          key: 'normal',
          prop: 'normal',
          title: '优先',
          children: [
            {
              dataIndex: 'normalCount',
              key: 'normalCount',
              prop: 'normalCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine == '合计' ? '' : row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '优先',
                  },
                })
              },
            },
            {
              dataIndex: 'normalRatio',
              key: 'normalRatio',
              prop: 'normalRatio',
              title: '占比',
            },
          ],
        },
        {
          dataIndex: 'strict',
          key: 'strict',
          prop: 'strict',
          title: '高风险',
          children: [
            {
              dataIndex: 'strictCount',
              key: 'strictCount',
              prop: 'strictCount',
              title: '件数',
              clickHandler: (row, rowIndex) => {
                this.$router.push({
                  path: './waybillTable',
                  name: 'WaybillTable',
                  params: {
                    startTime: this.FormData.beginDate,
                    endTime: this.FormData.endDate,
                    destination: row.flightLine == '合计' ? '' : row.flightLine,
                    agentCode: this.FormData.proxyId,
                    openResult: '',
                    riskRating: '高风险',
                  },
                })
              },
            },
            {
              dataIndex: 'strictRatio',
              key: 'strictRatio',
              prop: 'strictRatio',
              title: '占比',
            },
          ],
        },
      ],
      tableData: [],
      footerDate: [
        {
          flightLine: '合计',
          highRiskcount: '',
          lowRiskCount: '',
          priorityCount: '',
          normalCount: '',
          strictCount: '',
        },
      ],
      FormData: {
        beginDate: '',
        endDate: '',
        places: [],
        proxyId: '',
      },
    }
  },
  created() {
    this.formatDate()
    this.routdata()
  },
  mounted() {
    this.setTableHeight()
    window.addEventListener('resize', this.setTableHeight)
  },
  activated() {
    if (Object.keys(this.$route.params).length !== 0) {
      const { beginDate, endDate, places, proxyId } = this.$route.params
      this.FormData.beginDate = beginDate
      this.FormData.endDate = endDate
      if (places && typeof places == 'string') {
        this.FormData.places = [places]
      }
      if (places && typeof places != 'string') {
        this.FormData.places = places
      }
      this.FormData.proxyId = proxyId
    }
    this.getData()
  },
  beforeDestroy() {
    window.removeEventListener('resize', this.setTableHeight)
  },
  methods: {
    //切换单位
    ups(item, index) {
      this.active = index
      this.getData()
    },
    async exportex() {
      // let that = this;
      // this.$confirm({
      //   title: "是否确认导出",
      //   content: "此操作将导出当前条件下所有数据而非选中数据",
      //   onOk() {
      //     return agentexcl(this.FormData).then((response) => {
      //       that.download(response.msg);
      //       that.$message.success("导出成功", 3);
      //     });
      //   },
      // });
      this.downFile()
    },
    //导出
    downlodTable() {
      this.$confirm('是否需要导出xlsx文档, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(() => {
          this.downFile()
          this.$message({
            type: 'success',
            message: '导出成功!',
          })
        })
        .catch(() => {
          this.$message({
            type: 'info',
            message: '已取消导出',
          })
        })
    },
    downFile() {
      var wb = XLSX.utils.table_to_book(document.querySelector('#table1'))
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      })
      try {
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream',
          }),
          '航线货物关联统计.xlsx'
        )
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout)
      }
      return wbout
    },
    formatDate() {
      let date = new Date()
      let myyear = date.getFullYear()
      let mymonth = date.getMonth() + 1
      let myweekday = date.getDate()
      mymonth < 10 ? (mymonth = '0' + mymonth) : mymonth
      myweekday < 10 ? (myweekday = '0' + myweekday) : myweekday
      this.FormData.beginDate = `${myyear}-${mymonth}-${myweekday}`
      this.FormData.endDate = `${myyear}-${mymonth}-${myweekday}`
    },
    async routdata() {
      try {
        const result = await routeall({})
        if (result.status == 200) {
          this.destination = []
          result.data.forEach((element) => {
            let obj = {
              name: element,
              lable: element,
            }
            this.destination.push(obj)
          })
          this.destination.sort(this.up)
        }
      } catch (error) {
        console.log(error)
      }
    },
    up(x, y) {
      return x.lable.charCodeAt(0) - y.lable.charCodeAt(0)
    },
    //接口数据
    async getData() {
      try {
        this.loading = true
        const result = this.active == 0 ? await agent(this.FormData) : await agentPiece(this.FormData)
        if (result.status === 200) {
          this.tableData = result.data
          this.tableData.forEach((item) => {
            let arr = [{}, {}, {}, {}, {}]
            item.datas.forEach((data) => {
              data['mix'] = Math.floor((data.count / item.count) * 100) + '%'
              if (data.level == '普通') {
                arr[3] = data
              }
              if (data.level == '严控') {
                arr[1] = data
              }
              if (data.level == '低风险') {
                arr[2] = data
              }
              if (data.level == '优先') {
                arr[4] = data
              }
              if (data.level == '高风险') {
                arr[0] = data
              }
            })
            item.datas = arr
          })
          if (this.tableData.length > 0) {
            for (let i = 0; i < this.tableData[0].datas.length; i++) {
              this.tableCols.forEach((item) => {
                if (item.title == this.tableData[0].datas[i].level) {
                  item.prop = 'datas'
                  item.children[0].dataIndex = 'datas[' + i + '].count'
                  item.children[0].prop = 'datas[' + i + '].count'
                  item.children[1].dataIndex = 'datas[' + i + '].mix'
                }
              })
            }
          }
          let count = []
          let highRiskcount = []
          let lowRiskCount = []
          let priorityCount = []
          let normalCount = []
          let strictCount = []
          result.data.forEach((res) => {
            res.count ? count.push(res.count) : count.push(0)
            res.datas.forEach((re) => {
              if (re.level == '普通') {
                highRiskcount.push(re.count)
              } else if (re.level == '严控') {
                lowRiskCount.push(re.count)
              } else if (re.level == '低风险') {
                priorityCount.push(re.count)
              } else if (re.level == '优先') {
                normalCount.push(re.count)
              } else if (re.level == '高风险') {
                strictCount.push(re.count)
              }
            })
          })
          // console.log(this.tableCols)
          this.footerDate[0] = {
            flightLine: '合计',
            count: eval(count.join('+')),
            'datas[3].count': eval(highRiskcount.join('+')),
            'datas[1].count': eval(lowRiskCount.join('+')),
            'datas[2].count': eval(priorityCount.join('+')),
            'datas[4].count': eval(normalCount.join('+')),
            'datas[0].count': eval(strictCount.join('+')),
          }
          this.loading = false
        }
      } catch (error) {
        console.log(error)
      }
    },
    changeHandler() {
      let param = JSON.parse(JSON.stringify(this.FormData))
      param.places = param.places[0]
      this.$router.push({
        path: './cargoCharts',
        name: 'CargoCharts',
        params: this.FormData,
      })
    },
    searchHandler(arr) {
      if (typeof arr[1] == 'string' && arr[1] == '') {
        arr[1] = []
      }
      if (typeof arr[1] == 'string' && arr[1] != '') {
        arr[1] = [arr[1]]
      }
      this.FormData.beginDate = arr[0][0]
      this.FormData.endDate = arr[0][1]
      this.FormData.places = arr[1]
      this.FormData.proxyId = arr[2]
      this.getData()
    },
    setTableHeight() {
      const topBarHeight = 80
      const headerHeight = this.$refs['tableWrapperHeader'].offsetHeight
      const footerBlackHeight = 24
      this.tableHeight = `calc(100vh - ${topBarHeight + headerHeight + footerBlackHeight}px)-20px`
    },
  },
}
</script>

<style lang="scss" scoped>
.table-wrapper {
  padding: 0 24px;
  .conten {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 2px;
    .log_cont {
      width: 80px;
      height: 32px;
      display: flex;
      justify-content: space-between;
      align-items: center;
      background: #101116;
      border-radius: 4px;
      color: #ffffff;
      border: 2px solid #101116;
      > .cont {
        width: 50%;
        height: 100%;
        display: flex;
        justify-content: center;
        align-items: center;
        .log_type {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          cursor: pointer;
        }
        .log_types {
          width: 100%;
          height: 100%;
          display: flex;
          justify-content: center;
          align-items: center;
          background: #ffffff;
          color: #101116;
          cursor: pointer;
        }
      }
    }
  }
  // background: #dfe3ea;
  .table-header-wrapper {
    // padding-top: 24px;
  }
}
</style>
